<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { HomeFilled } from "@element-plus/icons-vue";
import axios from 'axios';
import request from '@/utils/request';
import { ElMessage } from 'element-plus';
// 导入知识图谱组件
import KnowledgeGraph from '@/components/KnowledgeGraph.vue';

function toggleChat() {
            const container = document.getElementById('chatContainer');
            if (container.style.display === 'none' || container.style.display === '') {
                container.style.display = 'block';
            } else {
                container.style.display = 'none';
            }
        }

const route = useRoute();
const router = useRouter();

const backToHome = () => {
    router.push('/student/Homepage/PersonalHomepage')
}

// 课程数据状态
const courseData = ref(null);
const loading = ref(true);
const error = ref(null);

// 知识图谱相关
const showKnowledgeGraph = ref(false);
const knowledgeGraphData = ref(null);

// 从路由参数获取当前课程ID
const courseId = computed(() => parseInt(route.query.id));

// 获取课程详情
const fetchCourseData = async () => {
    loading.value = true;
    error.value = null;

    try {
        if (!courseId.value) {
            throw new Error('未提供课程ID');
        }

        console.log(`尝试获取课程${courseId.value}的详情...`);
        const response = await request.get(`/api/student/course/${courseId.value}/`);
        console.log('课程详情响应:', response);

        // 确保响应有效性
        if (!response || !response.data) {
            throw new Error('服务器返回了空数据');
        }

        // 处理API直接返回数据的情况
        const responseData = response.data;
        console.log('处理的响应数据:', responseData);

        // 规范化数据结构，确保所有必需的字段都存在
        courseData.value = {
            id: responseData.id || courseId.value,
            name: responseData.name || `课程${courseId.value}`,
            description: responseData.description || '暂无描述',
            content: responseData.content || responseData.description || '暂无内容',
            chapters: responseData.chapters || [],
            stats: responseData.stats || { total_students: 0, completion_rate: 0 },
            created_at: responseData.created_at || new Date().toISOString(),
            updated_at: responseData.updated_at || new Date().toISOString()
        };

        // 尝试获取知识图谱数据
        fetchKnowledgeGraphData();

        console.log('处理后的课程数据:', courseData.value);
    } catch (err) {
        console.error('获取课程详情失败:', err);
        error.value = '获取课程详情失败，使用测试数据代替';

        // 使用根据课程ID定制的测试数据
        useTestCourseData(courseId.value);
    } finally {
        loading.value = false;
        // 确保courseData一定有值
        if (!courseData.value) {
            courseData.value = {
                id: courseId.value,
                name: `课程${courseId.value}`,
                description: '加载失败',
                content: '无法加载课程内容'
            };
        }
        console.log('最终使用的课程数据:', courseData.value);
    }
};

// 获取知识图谱数据
const fetchKnowledgeGraphData = async () => {
    try {
        if (!courseId.value) return;

        // 尝试从API获取知识图谱数据
        const response = await request.get(`/api/knowledge-graph/${courseId.value}/`);
        if (response && response.data) {
            knowledgeGraphData.value = response.data;
            console.log('获取到知识图谱数据:', knowledgeGraphData.value);
            return;
        }
    } catch (err) {
        console.error('获取知识图谱数据失败:', err);
    }

    // 如果API获取失败，使用课程数据生成知识图谱数据
    if (courseData.value && courseData.value.chapters) {
        const nodes = [];
        const links = [];

        // 添加课程节点
        const courseNodeId = `course-${courseId.value}`;
        nodes.push({
            id: courseNodeId,
            name: courseData.value.name,
            category: 'course',
            value: 50  // 较大节点
        });

        // 添加章节节点和链接
        courseData.value.chapters.forEach((chapter, index) => {
            if (!chapter.id || !chapter.title) return;

            // 章节节点ID
            const chapterNodeId = `chapter-${chapter.id}`;

            // 添加章节节点
            nodes.push({
                id: chapterNodeId,
                name: chapter.title,
                category: 'chapter',
                value: 30  // 中等节点
            });

            // 添加课程到章节的链接
            links.push({
                source: courseNodeId,
                target: chapterNodeId,
                relation: 'contains'
            });

            // 添加知识点节点和链接
            if (chapter.points && chapter.points.length) {
                chapter.points.forEach(point => {
                    if (!point.id || !point.title) return;

                    // 知识点节点ID
                    const pointNodeId = `point-${point.id}`;

                    // 添加知识点节点
                    nodes.push({
                        id: pointNodeId,
                        name: point.title,
                        category: 'point',
                        value: 20  // 较小节点
                    });

                    // 添加章节到知识点的链接
                    links.push({
                        source: chapterNodeId,
                        target: pointNodeId,
                        relation: 'contains'
                    });

                    // 如果有前一个知识点，添加顺序链接
                    if (index > 0) {
                        const prevChapter = courseData.value.chapters[index - 1];
                        if (prevChapter && prevChapter.points && prevChapter.points.length) {
                            const lastPoint = prevChapter.points[prevChapter.points.length - 1];
                            if (lastPoint && lastPoint.id) {
                                links.push({
                                    source: `point-${lastPoint.id}`,
                                    target: pointNodeId,
                                    relation: 'prerequisite'
                                });
                            }
                        }
                    }
                });
            }
        });

        // 检查并修复数据
        if (nodes.length === 0) {
            // 如果没有节点，添加一个默认节点
            nodes.push({
                id: 'default-node',
                name: courseData.value.name || '未知课程',
                category: 'course',
                value: 50
            });
        }

        knowledgeGraphData.value = { nodes, links };
        console.log('生成的知识图谱数据:', knowledgeGraphData.value);
    }
};

// 根据课程ID提供不同的测试数据
const useTestCourseData = (courseId) => {
    console.log(`为课程ID ${courseId} 生成测试数据`);
    const courseIdNum = Number(courseId);

    // 默认数据结构
    let testData = {
        id: courseIdNum,
        name: `测试课程${courseIdNum}`,
        description: '这是一个测试课程描述',
        content: '这是测试课程内容，实际内容将从数据库获取。',
        chapters: [],
        stats: {
            total_students: Math.floor(Math.random() * 100) + 20,
            completion_rate: Math.floor(Math.random() * 100)
        },
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString()
    };

    // 根据不同课程ID生成不同的测试数据
    switch(courseIdNum) {
        case 1: // 数据结构
            testData = {
                id: 1,
                name: '数据结构',
                description: '数据结构是计算机科学的基础课程，主要研究数据的逻辑结构及其基本操作。通过本课程，你将掌握常见数据结构及相关算法的设计与分析方法。',
                content: '本课程涵盖线性表、栈与队列、树、图等基本数据结构，以及查找、排序等经典算法。学习这些内容将帮助你理解数据的组织方式，为算法设计和程序优化打下坚实基础。课程采用理论与实践相结合的教学方法，通过丰富的编程实例加深理解。',
                chapters: [
                    {
                        id: 1,
                        title: '绪论',
                        order: 1,
                        points: [
                            { id: 1, title: '数据结构的基本概念' },
                            { id: 2, title: '算法分析基础' }
                        ]
                    },
                    {
                        id: 2,
                        title: '线性表',
                        order: 2,
                        points: [
                            { id: 3, title: '顺序表的实现与应用' },
                            { id: 4, title: '链表的实现与应用' }
                        ]
                    },
                    {
                        id: 3,
                        title: '栈与队列',
                        order: 3,
                        points: [
                            { id: 5, title: '栈的实现与应用' },
                            { id: 6, title: '队列的实现与应用' }
                        ]
                    },
                    {
                        id: 4,
                        title: '树与二叉树',
                        order: 4,
                        points: [
                            { id: 7, title: '二叉树的性质与遍历' },
                            { id: 8, title: 'AVL树与红黑树' }
                        ]
                    },
                    {
                        id: 5,
                        title: '图',
                        order: 5,
                        points: [
                            { id: 9, title: '图的存储结构' },
                            { id: 10, title: '图的遍历' },
                            { id: 11, title: '最短路径算法' }
                        ]
                    }
                ],
                stats: {
                    total_students: 87,
                    completion_rate: 68
                },
                created_at: '2025-03-15T08:00:00Z',
                updated_at: '2025-04-20T10:15:00Z'
            };
            break;

        case 2: // 操作系统
            testData = {
                id: 2,
                name: '操作系统',
                description: '操作系统是计算机系统的核心，负责管理计算机硬件与软件资源。本课程将介绍操作系统的基本原理、设计与实现。',
                content: '本课程涵盖进程管理、内存管理、文件系统、设备管理等核心内容，并介绍Linux、Windows等主流操作系统的特点。通过学习，你将理解计算机系统的工作原理，为后续学习分布式系统、云计算等高级课程奠定基础。课程包含理论讲解和实验操作两部分，帮助你掌握操作系统的关键概念和实际应用。',
                chapters: [
                    {
                        id: 6,
                        title: '操作系统概述',
                        order: 1,
                        points: [
                            { id: 12, title: '操作系统的功能与结构' },
                            { id: 13, title: '操作系统发展简史' }
                        ]
                    },
                    {
                        id: 7,
                        title: '进程管理',
                        order: 2,
                        points: [
                            { id: 14, title: '进程与线程' },
                            { id: 15, title: '进程调度算法' },
                            { id: 16, title: '进程同步与互斥' },
                            { id: 17, title: '死锁处理' }
                        ]
                    },
                    {
                        id: 8,
                        title: '内存管理',
                        order: 3,
                        points: [
                            { id: 18, title: '内存分配策略' },
                            { id: 19, title: '虚拟内存技术' },
                            { id: 20, title: '页面置换算法' }
                        ]
                    },
                    {
                        id: 9,
                        title: '文件系统',
                        order: 4,
                        points: [
                            { id: 21, title: '文件系统基础' },
                            { id: 22, title: '文件存储空间管理' },
                            { id: 23, title: '目录结构与文件共享' }
                        ]
                    },
                    {
                        id: 10,
                        title: '设备管理',
                        order: 5,
                        points: [
                            { id: 24, title: 'I/O系统' },
                            { id: 25, title: '磁盘调度算法' }
                        ]
                    }
                ],
                stats: {
                    total_students: 76,
                    completion_rate: 62
                },
                created_at: '2025-03-15T08:30:00Z',
                updated_at: '2025-04-25T11:20:00Z'
            };
            break;

        case 3: // 计算机网络
            testData = {
                id: 3,
                name: '计算机网络',
                description: '计算机网络是研究计算机之间如何通信和资源共享的学科。本课程将讲解网络通信的基本原理和协议。',
                content: '本课程采用自顶向下的方法，从应用层开始，依次介绍各层网络协议及其工作原理。主要内容包括物理层传输介质与信号编码、数据链路层的差错控制、网络层路由选择、传输层的可靠数据传输、应用层的主要协议等。通过本课程的学习，你将全面了解互联网的工作机制，能够进行简单的网络配置和故障排除。',
                chapters: [
                    {
                        id: 11,
                        title: '计算机网络概述',
                        order: 1,
                        points: [
                            { id: 26, title: '网络分类与拓扑结构' },
                            { id: 27, title: '网络性能指标' }
                        ]
                    },
                    {
                        id: 12,
                        title: '物理层',
                        order: 2,
                        points: [
                            { id: 28, title: '传输介质' },
                            { id: 29, title: '信号编码技术' }
                        ]
                    },
                    {
                        id: 13,
                        title: '数据链路层',
                        order: 3,
                        points: [
                            { id: 30, title: '差错检测与纠正' },
                            { id: 31, title: '以太网协议' }
                        ]
                    },
                    {
                        id: 14,
                        title: '网络层',
                        order: 4,
                        points: [
                            { id: 32, title: 'IP协议' },
                            { id: 33, title: '路由选择算法' },
                            { id: 34, title: 'ICMP协议' }
                        ]
                    },
                    {
                        id: 15,
                        title: '传输层',
                        order: 5,
                        points: [
                            { id: 35, title: 'TCP协议' },
                            { id: 36, title: 'UDP协议' },
                            { id: 37, title: '流量控制与拥塞控制' }
                        ]
                    },
                    {
                        id: 16,
                        title: '应用层',
                        order: 6,
                        points: [
                            { id: 38, title: 'DNS系统' },
                            { id: 39, title: 'HTTP协议' },
                            { id: 40, title: 'SMTP与POP3协议' }
                        ]
                    }
                ],
                stats: {
                    total_students: 92,
                    completion_rate: 75
                },
                created_at: '2025-03-18T09:00:00Z',
                updated_at: '2025-05-01T14:30:00Z'
            };
            break;

        case 4: // 数据库系统
            testData = {
                id: 4,
                name: '数据库系统',
                description: '数据库系统是管理和存储数据的专用软件系统，是信息系统的核心组件。本课程将介绍数据库的基本概念、原理和应用。',
                content: '本课程主要讲解关系型数据库系统，内容包括关系数据模型、SQL语言、数据库设计理论、事务处理等。同时也会简要介绍NoSQL数据库和新型数据库技术。通过本课程的学习，你将能够设计合理的数据库结构，编写高效的SQL查询，并理解数据库系统内部的工作机制。本课程注重理论与实践结合，设有多个数据库实验项目。',
                chapters: [
                    {
                        id: 17,
                        title: '数据库系统概论',
                        order: 1,
                        points: [
                            { id: 41, title: '数据管理技术的发展' },
                            { id: 42, title: '数据库系统的结构' }
                        ]
                    },
                    {
                        id: 18,
                        title: '关系数据模型',
                        order: 2,
                        points: [
                            { id: 43, title: '关系数据结构' },
                            { id: 44, title: '关系代数' },
                            { id: 45, title: '关系演算' }
                        ]
                    },
                    {
                        id: 19,
                        title: 'SQL语言',
                        order: 3,
                        points: [
                            { id: 46, title: '数据定义' },
                            { id: 47, title: '数据查询' },
                            { id: 48, title: '数据操纵' },
                            { id: 49, title: '视图与索引' }
                        ]
                    },
                    {
                        id: 20,
                        title: '数据库设计',
                        order: 4,
                        points: [
                            { id: 50, title: 'ER模型' },
                            { id: 51, title: '规范化理论' },
                            { id: 52, title: '数据库设计步骤' }
                        ]
                    },
                    {
                        id: 21,
                        title: '事务处理',
                        order: 5,
                        points: [
                            { id: 53, title: '事务的ACID特性' },
                            { id: 54, title: '并发控制' },
                            { id: 55, title: '恢复技术' }
                        ]
                    }
                ],
                stats: {
                    total_students: 81,
                    completion_rate: 70
                },
                created_at: '2025-03-20T10:15:00Z',
                updated_at: '2025-05-05T16:40:00Z'
            };
            break;

        case 5: // 软件工程
            testData = {
                id: 5,
                name: '软件工程',
                description: '软件工程是应用工程化方法构建和维护高质量软件的学科。本课程将介绍软件开发的各个阶段和方法学。',
                content: '本课程涵盖软件生命周期的各个阶段，包括需求分析、软件设计、编码实现、软件测试和维护等内容。同时还会介绍各种软件开发模型，如瀑布模型、增量模型、敏捷开发等。通过本课程的学习，你将掌握规范的软件开发方法，能够参与和管理中小型软件项目的开发过程。课程设有团队项目实践，培养学生的团队协作能力。',
                chapters: [
                    {
                        id: 22,
                        title: '软件工程概述',
                        order: 1,
                        points: [
                            { id: 56, title: '软件危机与软件工程' },
                            { id: 57, title: '软件生命周期' }
                        ]
                    },
                    {
                        id: 23,
                        title: '软件过程',
                        order: 2,
                        points: [
                            { id: 58, title: '瀑布模型' },
                            { id: 59, title: '增量模型' },
                            { id: 60, title: '敏捷开发' }
                        ]
                    },
                    {
                        id: 24,
                        title: '需求工程',
                        order: 3,
                        points: [
                            { id: 61, title: '需求获取' },
                            { id: 62, title: '需求分析与规格说明' },
                            { id: 63, title: '需求验证' }
                        ]
                    },
                    {
                        id: 25,
                        title: '软件设计',
                        order: 4,
                        points: [
                            { id: 64, title: '结构化设计方法' },
                            { id: 65, title: '面向对象设计方法' },
                            { id: 66, title: 'UML建模' }
                        ]
                    },
                    {
                        id: 26,
                        title: '软件测试',
                        order: 5,
                        points: [
                            { id: 67, title: '白盒测试' },
                            { id: 68, title: '黑盒测试' },
                            { id: 69, title: '单元测试与集成测试' }
                        ]
                    },
                    {
                        id: 27,
                        title: '软件维护与管理',
                        order: 6,
                        points: [
                            { id: 70, title: '软件配置管理' },
                            { id: 71, title: '软件质量保证' },
                            { id: 72, title: '软件项目管理' }
                        ]
                    }
                ],
                stats: {
                    total_students: 65,
                    completion_rate: 58
                },
                created_at: '2025-03-22T11:30:00Z',
                updated_at: '2025-05-10T09:15:00Z'
            };
            break;

        default: // 其他课程使用动态生成的数据
            const chapterCount = 3 + (courseIdNum % 4); // 3-6个章节
            const chapters = [];

            for (let i = 1; i <= chapterCount; i++) {
                const pointCount = 2 + (i % 3); // 每章节2-4个知识点
                const points = [];

                for (let j = 1; j <= pointCount; j++) {
                    points.push({
                        id: (i-1) * 5 + j,
                        title: `知识点${i}.${j}：${getRandomTopic(courseIdNum, i, j)}`
                    });
                }

                chapters.push({
                    id: i,
                    title: `第${i}章：${getRandomChapterTitle(courseIdNum, i)}`,
                    order: i,
                    points: points
                });
            }

            testData = {
                id: courseIdNum,
                name: `课程${courseIdNum}`,
                description: `这是课程${courseIdNum}的简要描述，介绍了该课程的主要内容和学习目标。`,
                content: `这是课程${courseIdNum}的详细介绍，包含了课程背景、教学方法、考核方式等信息。通过本课程的学习，你将掌握该领域的基本概念和核心技能。`,
                chapters: chapters,
                stats: {
                    total_students: Math.floor(Math.random() * 100) + 20,
                    completion_rate: Math.floor(Math.random() * 100)
                },
                created_at: new Date(Date.now() - Math.random() * 10000000000).toISOString(),
                updated_at: new Date(Date.now() - Math.random() * 1000000000).toISOString()
            };
    }

    // 将测试数据赋值给courseData
    courseData.value = testData;
};

// 生成随机章节标题
const getRandomChapterTitle = (courseId, chapterIndex) => {
    const titles = [
        ['基础概念', '核心原理', '关键技术', '实践应用', '前沿发展'],
        ['导论', '基本方法', '进阶内容', '实战技巧', '总结展望'],
        ['理论基础', '算法设计', '系统架构', '优化策略', '案例分析']
    ];

    const titleSet = titles[courseId % 3];
    return titleSet[chapterIndex % titleSet.length];
};

// 生成随机知识点
const getRandomTopic = (courseId, chapterIndex, pointIndex) => {
    const topics = [
        ['数据类型', '控制结构', '函数设计', '算法分析', '内存管理', '文件操作', '并发控制'],
        ['模型设计', '接口定义', '组件开发', '测试方法', '部署策略', '性能优化', '安全措施'],
        ['网络协议', '数据结构', '算法实现', '系统架构', '设计模式', '用户界面', '服务配置']
    ];

    const topicSet = topics[courseId % 3];
    return topicSet[(chapterIndex * 3 + pointIndex) % topicSet.length];
};

// 检查是否已选择
const isSelected = ref(false);
const fetchSelectionStatus = async () => {
    try {
        // 从本地存储获取学生信息
        const studentInfo = JSON.parse(localStorage.getItem('studentUserInfo') || '{}');
        if (!studentInfo || !studentInfo.stu_id) {
            return;
        }

        const response = await request.get('/api/student/course-selection/', {
            params: {
                stu_id: studentInfo.stu_id,
                course_id: courseId.value
            }
        });

        isSelected.value = Array.isArray(response.data)
            ? response.data.some(item => item === courseId.value || item.course_id === courseId.value)
            : false;
    } catch (err) {
        console.error('获取选课状态失败:', err);
        // 使用本地存储作为后备方案
        const selected = JSON.parse(localStorage.getItem('selectedCourses') || '[]');
        isSelected.value = selected.includes(courseId.value);
    }
};

// 切换选择状态
const toggleSelection = async () => {
    try {
        // 从本地存储获取学生信息
        const studentInfo = JSON.parse(localStorage.getItem('studentUserInfo') || '{}');
        if (!studentInfo || !studentInfo.stu_id) {
            ElMessage.warning('请先登录');
            return;
        }

        if (isSelected.value) {
            // 取消选课
            await request.delete(`/api/student/course-selection/${courseId.value}/`, {
                params: { stu_id: studentInfo.stu_id }
            });
        } else {
            // 选课
            await request.post('/api/student/course-selection/', {
                stu_id: studentInfo.stu_id,
                course_id: courseId.value
            });
        }

        // 更新选课状态
        isSelected.value = !isSelected.value;

        // 更新本地存储，作为后备方案
    let selected = JSON.parse(localStorage.getItem('selectedCourses') || '[]');
        if (isSelected.value) {
            if (!selected.includes(courseId.value)) {
        selected.push(courseId.value);
            }
    } else {
            selected = selected.filter(id => id !== courseId.value);
        }
        localStorage.setItem('selectedCourses', JSON.stringify(selected));

        ElMessage.success(isSelected.value ? '选课成功' : '已取消选课');
    } catch (err) {
        console.error('选课操作失败:', err);
        ElMessage.error('操作失败，请重试');
    }
};

// 切换知识图谱显示状态
const toggleKnowledgeGraph = () => {
    showKnowledgeGraph.value = !showKnowledgeGraph.value;
    if (showKnowledgeGraph.value && !knowledgeGraphData.value) {
        fetchKnowledgeGraphData();
    }
};

// 页面加载时获取数据
onMounted(() => {
    console.log('CourseDetail组件已挂载，courseId:', courseId.value);
    fetchCourseData();
    fetchSelectionStatus();
});

const AItoggleChat = () => {
    const container = document.getElementById('chatContainer');
    if (container.style.display === 'none' || container.style.display === '') {
        container.style.display = 'block';
    } else {
        container.style.display = 'none';
    }
}

</script>

<template>
    <el-container>
        <el-header style="padding: 20px">
            <el-row>
                <el-col :span="2">
                    <el-icon size="30" color="black">
                        <HomeFilled @click="backToHome"/>
                    </el-icon>
                </el-col>
                <el-col :span="20">
                    <div style="text-align: center; font-size: large">
                        课程详情
                    </div>
                </el-col>
                <el-col :span="2" />
            </el-row>
        </el-header>
        <el-main>
            <div v-loading="loading" class="detail-container">
                <el-button type="primary" @click="router.back()" class="back-btn">返回</el-button>
                <el-card v-if="courseData" class="detail-card">
                    <template #header>
                        <h2>{{ courseData.name }}</h2>
                    </template>

                    <div class="course-info">
                        <p><strong>课程描述:</strong> {{ courseData.description }}</p>
                        <div class="course-content">
                            <h3>课程内容</h3>
                            <p>{{ courseData.content }}</p>
                        </div>

                        <el-button
                            :type="isSelected ? 'success' : 'primary'"
                            @click="toggleSelection"
                            class="select-btn"
                        >
                            {{ isSelected ? '已选择' : '选择课程' }}
                        </el-button>
                    </div>
                </el-card>

                <!-- 知识图谱部分 -->
                <div class="knowledge-graph-section">
                    <div class="section-header">
                        <h3>课程知识图谱</h3>
                        <el-button
                            type="primary"
                            text
                            @click="toggleKnowledgeGraph"
                        >
                            {{ showKnowledgeGraph ? '收起' : '展开' }}
                        </el-button>
                    </div>

                    <div v-if="showKnowledgeGraph" class="graph-container">
                        <div class="graph-loading-container" v-if="!courseId">
                            <el-empty description="未找到课程信息" />
                        </div>
                        <template v-else>
                            <!-- 直接嵌入知识图谱组件 -->
                            <div class="graph-component-container">
                                <div v-if="knowledgeGraphData" style="height: 500px; width: 100%;">
                                    <KnowledgeGraph :graph-data="knowledgeGraphData" />
                                </div>
                                <div v-else class="graph-loading-container">
                                    <el-skeleton :rows="6" animated />
                                </div>
                            </div>

                            <div class="graph-view-link">
                                <el-button
                                    type="primary"
                                    @click="router.push(`/student/course/knowledge-graph/${courseId}`)"
                                >
                                    在新页面查看完整知识图谱
                                </el-button>
                            </div>
                        </template>
                    </div>
                </div>

                <!-- 章节列表 -->
                <div v-if="courseData && courseData.chapters && courseData.chapters.length > 0" class="chapters-section">
                    <h3>课程章节</h3>
                    <el-collapse>
                        <el-collapse-item v-for="chapter in courseData.chapters" :key="chapter.id" :title="chapter.title || '未命名章节'">
                            <div class="chapter-content">
                                <p>章节序号: {{ chapter.order || '未知' }}</p>
                                <div v-if="chapter.points && chapter.points.length > 0">
                                    <h4>知识点:</h4>
                                    <ul>
                                        <li v-for="point in chapter.points" :key="point.id">
                                            {{ point.title || '未命名知识点' }}
                                        </li>
                                    </ul>
                                </div>
                            </div>
                        </el-collapse-item>
                    </el-collapse>
            </div>

                <!-- 课程统计信息 -->
                <el-card v-if="courseData && courseData.stats" class="stats-card">
                    <template #header>
                        <h3>课程统计</h3>
                    </template>
                    <div class="stats-content">
                        <p><strong>已选学生:</strong> {{ courseData.stats.total_students || 0 }} 人</p>
                        <p><strong>完成率:</strong> {{ courseData.stats.completion_rate || 0 }}%</p>
                    </div>
                </el-card>

                <div v-if="!courseData && !loading">
                <el-empty description="课程不存在" />
                </div>
            </div>
        </el-main>
    </el-container>
    <div class="chat-bubble" @click="toggleChat">
        <img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='white'%3E%3Cpath d='M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z'/%3E%3C/svg%3E" alt="聊天">
    </div>

    <div class="chat-container" id="chatContainer">
        <iframe src="http://121.40.242.43/chatbot/W6TLrJcFFhFE1Zpi" class="chat-iframe"></iframe>
    </div>
</template>

<style scoped>
.detail-container {
    max-width: 1000px;
    margin: 0 auto;
    padding: 20px;
}

.back-btn {
    margin-bottom: 20px;
}

.error-alert {
    margin-bottom: 20px;
}

.detail-card {
    margin-bottom: 30px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.course-info {
    padding: 10px;
}

.course-content {
    margin-top: 20px;
    margin-bottom: 30px;
}

.select-btn {
    margin-top: 20px;
}

.knowledge-graph-section {
    margin-top: 30px;
    background-color: #f5f7fa;
    border-radius: 8px;
    padding: 15px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
}

.section-header h3 {
    margin: 0;
}

.graph-container {
    min-height: 500px;
    background-color: white;
    border-radius: 4px;
    border: 1px solid #ebeef5;
    overflow: hidden;
}

.graph-loading-container {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 400px;
}

.graph-component-container {
    padding: 15px;
    background-color: white;
    border-radius: 4px;
}

.graph-placeholder {
    padding: 10px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
}

.placeholder-content {
    margin-top: 10px;
}

.graph-nodes {
    margin-bottom: 10px;
}

.root-node {
    font-weight: bold;
    text-align: center;
    padding: 10px 15px;
    background-color: #409EFF;
    color: white;
    border-radius: 6px;
    margin: 0 auto 20px auto;
    max-width: 200px;
}

.connections {
    margin-top: 10px;
    position: relative;
    display: flex;
    justify-content: space-around;
}

.chapter-node {
    margin-bottom: 5px;
    padding: 8px 12px;
    background-color: #67C23A;
    color: white;
    border-radius: 4px;
    text-align: center;
    position: relative;
    max-width: 150px;
}

.chapter-node::before {
    content: '';
    position: absolute;
    top: -10px;
    left: 50%;
    width: 2px;
    height: 10px;
    background-color: #909399;
}

.point-connections {
    margin-left: 0;
    margin-top: 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.point-node {
    margin-bottom: 5px;
    padding: 5px 8px;
    background-color: #E6A23C;
    color: white;
    border-radius: 4px;
    text-align: center;
    position: relative;
    font-size: 0.9em;
    max-width: 140px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.point-node::before {
    content: '';
    position: absolute;
    top: -10px;
    left: 50%;
    width: 2px;
    height: 10px;
    background-color: #909399;
}

.more-node {
    margin-top: 5px;
    font-style: italic;
    color: #909399;
    text-align: center;
}

.empty-graph {
    text-align: center;
}

.graph-view-link {
    text-align: center;
    margin-top: 15px;
    padding: 10px;
}

.chapters-section {
    margin-top: 30px;
    background-color: #f5f7fa;
    border-radius: 8px;
    padding: 15px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.chapters-section h3 {
    margin-bottom: 15px;
}

.chapter-content {
    padding: 10px;
}

.stats-card {
    margin-top: 30px;
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.stats-content {
    padding: 10px;
}
.chat-bubble {
    position: fixed;
    bottom: 20px;
    right: 20px;
    width: 60px;
    height: 60px;
    background-color: #007bff;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    box-shadow: 0 2px 10px rgba(0,0,0,0.2);
    z-index: 1000;
}

.chat-bubble img {
    width: 30px;
    height: 30px;
}

.chat-container {
    position: fixed;
    bottom: 100px;
    right: 20px;
    width: 350px;
    height: 500px;
    background: white;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.2);
    display: none;
    z-index: 999;
}

.chat-iframe {
    width: 100%;
    height: 100%;
    border: none;
    border-radius: 10px;
}
</style>